/////////////////////////////////////////////////////////////////////////
//	AUTHOR: 		Eric IJzer                                         //
//	FILE:			Connection.cpp                         		       //
//	DESCRIPTION:	Implementation file of connection class			   //
/////////////////////////////////////////////////////////////////////////

#include "Connection.h"

/*
 *	Create new connection
 */
Connection::Connection() {
	// Get portnumber
	int portNumber = GetPortNumber();

	// Create server socket
	TCPSocket serverSocket(portNumber, 10);

	// Start server
	StartServer(serverSocket);
}

/*
 *	Get portnumber from user
 *
 *	Return: A valid portnumber
 */
int Connection::GetPortNumber() {
	// Local variables
	string input;
	int port;

	// Get user input
	cout << "Please enter a valid portnumber: ";
	cin >> input;

	// Try to parse input to an int
	std::istringstream iss(input);

	// input is numeric
	if(iss >> port) {
		// portnumer is in the valid range
		if(port > 0 && port <= 65535) {
			return port;
		}
		// portnumer is not in the valid range
		else {
			// Clear screen
			printf("\033[2J");

			cout << "Portnumber must be between 0 and 65536." << endl;
			return GetPortNumber();
		}
	}
	// input is not numeric
	else {
		// Clear screen
		printf("\033[2J");

		cout << "Input is not numeric, please enter a valid number." << endl;
		return GetPortNumber();
	}
}

/*
 * Start accepting connections
 */
void Connection::StartServer(TCPSocket socket) {
	// Main loop of connections
	while(true) {
		TCPSocket* sock = socket.Accept();
	}
}
